import json
import logging

from app.schemas.stomp import StompCommand, StompFrame
from app.websocket.connection_manager import manager

logger = logging.getLogger(__name__)


async def handle_stomp_message(user_id: str, frame: StompFrame):
    if frame.command == StompCommand.CONNECT:
        # 前端通常在 CONNECT 帧中带 token，但我们已在握手时认证
        ack_frame = StompFrame(command=StompCommand.CONNECTED, headers={"version": "1.2", "heart-beat": "4000,4000"})
        return ack_frame.to_frame()

    elif frame.command == StompCommand.SUBSCRIBE:
        destination = frame.headers.get("destination", "")
        if destination.startswith("/topic/"):
            topic = destination.replace("/topic/", "", 1)
            await manager.subscribe(user_id, topic)
        elif destination.startswith("/user/queue/"):
            # 点对点：自动订阅用户私有队列
            pass  # 可扩展
        return None

    elif frame.command == StompCommand.SEND:
        destination = frame.headers.get("destination", "")
        body = frame.body

        if destination == "/app/broadcast":
            # 广播消息
            await manager.broadcast_to_topic("notice", body)
        elif destination.startswith("/app/sendToUser/"):
            target_user = destination.replace("/app/sendToUser/", "", 1)
            # 构造私有消息帧
            private_frame = StompFrame(
                command=StompCommand.SEND, headers={"destination": "/user/queue/greeting"}, body=body
            ).to_frame()
            await manager.send_to_user(target_user, private_frame)
        elif destination == "/app/dict-update":
            # 字典更新通知（后端主动触发）
            data = json.loads(body)
            await manager.broadcast_to_topic("dict", json.dumps(data))
        return None

    elif frame.command == StompCommand.DISCONNECT:
        return None  # 连接关闭由 WebSocket 层处理

    return None
